package com.bc66.tiger.dict.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hsqldb.lib.StringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.support.ServletContextResource;

import com.bc66.tiger.dict.model.EnumDict;
import com.bc66.tiger.dict.service.IEnumDictService;

public class EnumDictServiceImpl extends DefaultResourceLoader implements IEnumDictService, InitializingBean, ServletContextAware {

	private static transient Log logger = LogFactory.getLog(EnumDictServiceImpl.class);

	private ServletContext servletContext;
	private ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver(this);
	private String[] baseDirs;
	private Map<String, Properties> dictPropertiesList = new HashMap<String, Properties>();
	
	public ResourcePatternResolver getResourceLoader() {
		return resourceLoader;
	}

	public String[] getBaseDirs() {
		return baseDirs;
	}

	public void setBaseDirs(String[] baseDirs) {
		this.baseDirs = baseDirs;
	}

	public Map<String, Properties> getDictPropertiesList() {
		return dictPropertiesList;
	}
	
	public void addDictProperties(String key, Properties properties){
		dictPropertiesList.put(key, properties);
	}
	
	public Properties getDictProperty(String dictType){
		return dictPropertiesList.get(dictType);
	}
	
	/**
	 * 
	 * @param dictType
	 * @param dictValue
	 * @return
	 */
	@Override
	public Double getDictDescAsDouble(String dictType, String dictValue){
		String value = getDictDesc(dictType, dictValue);
		if(value!=null){
			return Double.valueOf(value);
		}else{
			return null;
		}
	}
	
	/**
	 * 
	 * @param dictType
	 * @param dictValue
	 * @return
	 */
	@Override
	public Integer getDictDescAsInteger(String dictType, String dictValue){
		String value = getDictDesc(dictType, dictValue);
		if(value!=null){
			return Integer.valueOf(value);
		}else{
			return null;
		}
	}

	/**
	 * 
	 * @param dictType
	 * @param dictValue
	 * @return
	 */
	@Override
	public String getDictDesc(String dictType, String dictValue){
		String value = getDictProperty(dictType).getProperty(dictValue);
		try {
			return new String(value.getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取字典列表
	 * @param dictType
	 * @return
	 */
	@Override
	public List<EnumDict> getDictList(String dictType){
		Properties dictTypeProp = getDictProperty(dictType);
		Enumeration enumValues = dictTypeProp.keys();
		List<EnumDict> dictList = new ArrayList<EnumDict>();
		while (enumValues.hasMoreElements()) {
			String value = (String) enumValues.nextElement();
			if(!value.equals("dictType")){
				dictList.add(new EnumDict(value, dictTypeProp.getProperty(value)));
			}
		}
		return dictList;		
	}
	
	protected void loadProperties(String baseDir){
		try {
			Resource[] resArr = getResourceLoader().getResources(baseDir);
			for (int i = 0; i < resArr.length; i++) {
				Resource res = resArr[i];
				this.loadProperties(res);
			}
		} catch (IOException e) {
			logger.fatal("加载数据字典失败！",e);
		}
	}
	
	protected void loadProperties(Resource res) throws IOException{
		Properties prop = new Properties();
		InputStream inputStream = null;
		try {
			inputStream = res.getInputStream();
			prop.load(inputStream);
		} finally{
			try {
				inputStream.close();
			} catch (IOException e) {
				logger.fatal("关闭数据字典流失败！",e);
			}
		}
		String key = prop.getProperty("dictType");
		if(StringUtil.isEmpty(key)){
			logger.fatal("数据字典文件中未指定dictType，加载失败！");
		}else if(dictPropertiesList.containsKey(key)){
			logger.fatal("数据字典加载失败，指定的dictType[" + key + "]重复出现！");
		}else{
			addDictProperties(key, prop);
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(baseDirs==null) return;
		for (int i = 0; i < baseDirs.length; i++) {
			loadProperties(baseDirs[i]);
		}
	}
	
	@Override
	protected Resource getResourceByPath(String path) {
		return new ServletContextResource(this.servletContext, path);
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
